<template>
  <el-form :model="addForm" label-width="100px" :show-message="false" :rules="addFormRules" ref="addForm">
    <el-form-item label="展示门店:" prop="storeIds">
      <el-select
        clearable
        style="width: 560px"
        v-model="addForm.storeIds"
        multiple
        placeholder="所属门店"
      >
        <el-option
          v-for="item in stores"
          :key="item.id"
          :value="item.id"
          :label="item.storeName"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="广告类型:" prop="type">
      <el-select clearable v-model="addForm.type" placeholder="选择广告类型" style="width: 100%">
        <el-option
          v-for="item in dict.types"
          :key="item"
          :value="item"
          :label="item"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="广告位置:" prop="type">
      <el-select clearable v-model="addForm.site" placeholder="选择广告位置" style="width: 100%">
        <el-option
          v-for="item in dict.sites"
          :key="item"
          :value="item"
          :label="item"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="广告标题:" prop="title">
      <el-input v-model="addForm.title" clearable maxlength="20" placeholder="广告标题"></el-input>
    </el-form-item>
    <el-form-item label="广告备注:" prop="remark">
      <el-input v-model="addForm.remark"  maxlength="200" clearable placeholder="请输入广告备注" auto-complete="off"></el-input>
    </el-form-item>
    <el-form-item label="点击跳转Url:" prop="remark">
      <el-input v-model="addForm.url"  maxlength="200" clearable placeholder="请输入跳转URL" auto-complete="off"></el-input>
    </el-form-item>
    <el-form-item label="广告图片:" >
      <el-upload
        :action="values.uploadUrl"
        :headers="values.headers"
        :data="values.data"
        accept="image/png, image/jpeg"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :on-progress="uploadProgress"
        :on-success="uploadSuccess"
        :on-error="uploadError"
        :file-list="editFiles"
        :before-upload="beforeAvatarUpload"
        :limit="4">
        <i class="el-icon-plus"></i>
        <div class="el-upload__tip" slot="tip">只能上传jpg/png格式的图片,且不超过500kb，尺寸：674*336，图片必填;</div>
      </el-upload>
      <el-dialog
        width="50%"
        :visible.sync="dialogVisibleImage"
        append-to-body>
        <img width="100%"  :src="dialogImageUrl" alt="">
      </el-dialog>
    </el-form-item>
    <el-row>
      <el-col :span="24" align="center">
        <el-button type="primary" @click="onSubmit">保存</el-button>
      </el-col>
    </el-row>

  </el-form>
</template>

<script>
  import { details } from  '@/api/after-sale/systemManage/advert'
  import { getImageUrl } from '@/utils/index'
  import {beforeAvatarUpload} from '@/utils/beforeUpload'
  import { uploadUrl } from '@/api/after-sale/upload'
  import { getToken } from '@/utils/auth'
  import { JobShop } from '@/components/index'
  import { mapGetters } from 'vuex'
  export default {
    components: {JobShop},
    name: 'DialogDataForm',
    props: {
      advert: {
        type: Object,
        default: () => ({})
      },
    },
    data() {
      return {
        dict: {
          sites: ['首页广告', '登录页广告'],
          types: ['PC端', 'APP端']
        },
        dialogImageUrl:'',
        dialogVisibleImage:false,
        handleDataView: false,
        uploadComplete: true,
        editFiles:[],
        values: {
          uploadUrl: uploadUrl,
          headers: { 'token': getToken() },
          data: {
            prefixMenu: 'image',
          }
        },
        addForm: {
          type: '',
          title: '',
          remark: '',
          storeIds: [],
          photos: []
        },
        addFormRules: {
          storeIds: [{required: true}],
          type: [{required: true, trigger: 'change'}],
          title: [{required: true, trigger: 'blur'}],
          photos: [{required: true, trigger: 'change'}],
        }
      }
    },
    async created() {
      if (this.advert.id){
        const { data } = await details(this.advert.id);
        data.storeIds = [data.storeId];
        data.photos = data.photos?data.photos.split(','):'',
        data.photos.forEach((item, index) => {
          this.editFiles.push({
            name: index,
            url: getImageUrl(item),
          })
        })
        this.addForm = data;
      }
    },
    methods: {
      onSubmit() {
        this.$refs.addForm.validate(valid => {
          if (valid) {
            if(this.addForm.photos.length > 0){
              let options = JSON.parse(JSON.stringify(this.addForm));
              options.storeIds = options.storeIds.join(',');
              options.photos = options.photos.join(',');
              if (!options.id) {
                this.$emit('operate', options, 'send')
              } else {
                this.$emit('operate', options, 'update')
              }
            } else {
              this.$message.error('广告图片必填')
            }
          } else {
            return false
          }
        })
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url
        this.dialogVisibleImage = true
      },
      handleRemove(file, fileList) {
        this.addForm.photos = [];
        for(let fi of fileList){
          this.addForm.photos.push(fi.url);
        }
      },
      // 上传图片时调用
      uploadProgress() {
        this.uploadComplete = false
      },
      uploadSuccess(res) {
        this.uploadComplete = true
        this.fileChange(res)
      },
      uploadError() {
        this.$message.error('上传出错')
      },
      fileChange(res) {
        let photos = [res.data.id]
        this.addForm.photos = [...this.addForm.photos, ...photos] ;
      },
      beforeAvatarUpload(file){
        return beforeAvatarUpload(file);
      }
    },
    mounted() {
      tinymce.init({
        selector: '#tinydemo',
        language:'zh_CN',//注意大小写
      });
    },
    computed: {
      ...mapGetters(['stores', 'storesCalue']),
    },
  }
</script>
<style lang="scss" scoped>
</style>

